<!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Chat Room</title>
</head>
<body>
    <textarea id="chat-log" cols="100" rows="20"></textarea><br>
    <input id="chat-message-input" type="text" size="100"><br>
    <input id="chat-message-submit" type="button" value="Send">
    {{ group.id|json_script:"group-id" }}
    {{ user.id|json_script:"user-id" }}
    <script>
        const groupId = JSON.parse(document.getElementById('group-id').textContent);
        const userId = JSON.parse(document.getElementById('user-id').textContent);

        const chatSocket = new WebSocket('ws://'+ window.location.host+ '/ws/chat/' + '?user_id=' + userId + '&group_id=' + groupId);

        chatSocket.onopen = function() {
            chatSocket.send(JSON.stringify({
                'type': 'onopen'
            }));
        };
        chatSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);
            if (data.error) {
                alert(data.error);
                return 
            }
            document.querySelector('#chat-log').value += (data.message + '\n');
        };

        chatSocket.onclose = function(e) {
            console.error('Chat socket closed unexpectedly');
        };

        document.querySelector('#chat-message-input').focus();
        document.querySelector('#chat-message-input').addEventListener('keyup', function(event) {
            if (e.key === 'Enter') {  // enter, return
                document.querySelector('#chat-message-submit').click();
            }
        });

        document.querySelector('#chat-message-submit').onclick = function(e) {
            const messageInputDom = document.querySelector('#chat-message-input');
            const message = messageInputDom.value;
            chatSocket.send(JSON.stringify({
                'type': 'onmessage',
                'message': message
            }));
            messageInputDom.value = '';
        };
    </script>
</body>
</html>